/**
 * Created by Mark_ren on 2016/10/13.
 * 苟富贵、無相忘
 */
var express = require('express');
var router = express.Router();
var co = require('co');
var seqModule = require('./createModules');
var seq = new seqModule();
var formidable = require('formidable');
var getIP = require('./getIP');

//登录
router.get('/userLogin', function (req, res, next) {
    co(function() {
        var params = {};
        var paramT = {};
        console.log(req.query.loginName);
        console.log(req.query.passWord);
        params["loginName"] = req.query.loginName;
        params["passWord"] = req.query.passWord;
        paramT["where"] = params;
        // seq.sequelize.query("select * from power_user").then(function(result){
        //       console.log(result);
        // });
        seq.userModule.findAll(paramT).then(function (result) {
            if (result != null && result != "") {
                res.json({"success": true, "msg": "登录成功", "result": result});
            } else {
                res.json({"success": false, "msg": "登录失败,请重新输入", "result": result});
            }

        });
    }).catch(function (e) {
        res.json({'success': false, 'msg': '查询失败'});
        console.log(e);
    })
});


//查询
router.get('/getPowerUserPage', function(req, res, next) {
    co(function () {
        var page = parseInt(req.query.page);
        var params={};
        var paramT={};
        var paramU={};
        var paramV={};
        var include=[{model:seq.powerRoleModule}];
        paramT["include"]=include;
        if(req.query.id != undefined){
            params["id"]=req.query.id;
        }
        if(req.query.loginName != undefined){
            paramV["$like"]="%"+req.query.loginName+"%";
            params["loginName"]=paramV;
        }
        //模糊查询
        if(req.query.userName != undefined){
            paramU["$like"]="%"+req.query.userName+"%";
            params["userName"]=paramU;
        }
        if(req.query.passWord != undefined){
            params["passWord"]=req.query.passWord;
        }
        if(req.query.email != undefined){
            params["email"]=req.query.email;
        }
        if(req.query.tel != undefined){
            params["tel"]=req.query.tel;
        }
        if(req.query.roleId != undefined){
            params["roleId"]=req.query.roleId;
        }
        paramT["where"]=params;
        paramT["order"]=[["updateTime",'DESC']];
        if(req.query.page != undefined && req.query.rows !=undefined){
            paramT["offset"]=parseInt(req.query.page);
            paramT["limit"]=parseInt(req.query.rows);
        }
        seq.userModule.findAndCountAll(paramT).then(function(result){
            res.json({"success":true,"msg":"查询成功","page":page,"total":result.count,"result":result.rows});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});

router.get('/getPowerUsers', function(req, res, next) {
    co(function () {
        var params={};
        var paramT={};
        var paramU={};
        var paramV={};
        if(req.query.id != undefined){
            params["id"]=req.query.id;
        }
        if(req.query.loginName != undefined){
            paramV["$like"]="%"+req.query.loginName+"%";
            params["loginName"]=paramV;
        }
        //模糊查询
        if(req.query.userName != undefined){
            paramU["$like"]="%"+req.query.userName+"%";
            params["userName"]=paramU;
        }
        if(req.query.passWord != undefined){
            params["passWord"]=req.query.passWord;
        }
        if(req.query.email != undefined){
            params["email"]=req.query.email;
        }
        if(req.query.tel != undefined){
            params["tel"]=req.query.tel;
        }
        if(req.query.roleId != undefined){
            params["roleId"]=req.query.roleId;
        }
        paramT["where"]=params;
        paramT["order"]=[["updateTime",'DESC']];
        seq.userModule.findAll(paramT).then(function(result){
            res.json({"success":true,"msg":"查询成功","result":result});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});

router.post('/addPowerUser', function(req, res, next) {
    co(function () {
        if (req.method.toLowerCase() == 'post') {
            var form = new formidable.IncomingForm();
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                seq.userModule.create(fields).then(function (results) {
                    res.redirect(getIP+'power/powerUserList.html');
                });
            });
        }
    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});

//修改
router.post('/updatePowerUser', function(req, res, next) {
    co(function () {
        if (req.method.toLowerCase() == 'post') {
            var form = new formidable.IncomingForm();
            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                var params = {};
                var paramT = {};
                var paramU = {};
                paramU.id = fields.id;
                if(fields.loginName != undefined){
                    params["loginName"]=fields.loginName;
                }
                //模糊查询
                if(fields.userName != undefined){
                    params["userName"]=fields.userName;
                }
                if(fields.passWord != undefined){
                    params["passWord"]=fields.passWord;
                }
                if(fields.email != undefined){
                    params["email"]=fields.email;
                }
                if(fields.tel != undefined){
                    params["tel"]=fields.tel;
                }
                if(fields.powerRoleId != undefined){
                    params["powerRoleId"]=fields.powerRoleId;
                }
                if(fields.updateTime != undefined){
                    params.updateTime = fields.updateTime;
                }
                if(fields.updateUserName != undefined){
                    params.updateUserName = fields.updateUserName;
                }
                paramT.where = paramU
                seq.userModule.update(params,paramT).then(function (results) {
                    res.redirect(getIP+'power/powerUserList.html');
                });
            });
        }
    }).catch(function(e) {
        res.json({'success':false,'msg':'修改失败'});
        console.log(e);
    })
});


//删除
router.get('/deletePowerUser', function(req, res, next) {
    co(function () {
        var params=req.query.params;
        var arr=params.split(",");
        var paramT=[arr];
        seq.userModule.destroy({'where':{'id':paramT}}).then(function(results){
            res.json({"success":true,"msg":"删除成功","rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'删除失败'});
        console.log(e);
    })
});

module.exports = router;